package com.quectel.cms.controller.scheduling;


import com.quectel.cms.controller.BaseController;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.scheduling.dto.SchedulingAttendanceMonthDto;
import com.quectel.core.module.scheduling.service.SchedulingAttendanceMonthService;
import com.quectel.util.common.*;
import com.quectel.util.kit.PageFetchKit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.compress.utils.Lists;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

import static com.quectel.constant.global.StatisticsConstants.TIME_RANGE_BY_MONTH;

/**
 *
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/07/27 14:51
 */
@RestController
@RequestMapping("schedulingAttendanceMonth")
@Tag(name = "SchedulingAttendanceMonthController", description = "月度考勤汇总相关api 请开发者检查描述")
public class SchedulingAttendanceMonthController extends BaseController {

    @DubboReference
    private SchedulingAttendanceMonthService schedulingAttendanceMonthService;

    /**
     * 导出月度汇总记录
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "schedulingAttendanceMonth:exportExcel")
    public void exportParkExcel(@RequestParam Map<String, Object> params, HttpServletResponse httpServletResponse) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        if (!params.containsKey(SystemConstants.TIME_SLOT_KEY_PAIR.getLeft()) || !params.containsKey(SystemConstants.TIME_SLOT_KEY_PAIR.getRight())) {
            POIUtils.exportExcel(httpServletResponse, "月度汇总记录", new String[]{"月度范围必传"}, Lists.newArrayList(), "月度汇总记录");
            return ;
        }
        Response<Object> checkResponse = checkTimeRange(TIME_RANGE_BY_MONTH, params.get(SystemConstants.TIME_SLOT_KEY_PAIR.getLeft()) + " 00:00:00"
                , params.get(SystemConstants.TIME_SLOT_KEY_PAIR.getRight()) + " 00:00:00", 36);
        if (!checkResponse.isSuccess()) {
            POIUtils.exportExcel(httpServletResponse, "月度汇总记录", new String[]{checkResponse.getMessage()}, Lists.newArrayList(), "月度汇总记录");
            return ;
        }

        List<SchedulingAttendanceMonthDto> result = PageFetchKit.fetchAll(r -> schedulingAttendanceMonthService.queryList(r), request.getParams());
        String[] headers = new String[]{"月份", "所属小区", "工号", "姓名", "部门", "应出勤时长", "实际出勤时长(h)", "请假时长(h)", "出差时长(h)", "外出时长(h)", "加班时长(h)", "迟到次数", "早退次数", "缺卡次数", "应出勤天数", "实际出勤天数"};
        List<String[]> dataList = new ArrayList<>();

        for (SchedulingAttendanceMonthDto data : result) {
            String[] item = new String[headers.length];
            item[0] = Objects.nonNull(data.getMonth()) ? DateUtils.format(data.getMonth(), DateUtils.FormatType.MONTH) : "";
            item[1] = Objects.nonNull(data.getVillage()) ? data.getVillage().getName() : "";
            item[2] = data.getPersonJobNo();
            item[3] = data.getPersonName();
            String deptName = "";
            if (Objects.nonNull(data.getDeptPerson()) && Objects.nonNull(data.getDeptPerson().getDept())) {
                deptName = data.getDeptPerson().getDept().getName();
            }
            item[4] = deptName;
            item[5] = Objects.nonNull(data.getAttendanceHour()) ? data.getAttendanceHour().toPlainString() : "";
            item[6] = Objects.nonNull(data.getRealityAttendanceHour()) ? data.getRealityAttendanceHour().toPlainString() : "";
            item[7] = Objects.nonNull(data.getLeaveHour()) ? data.getLeaveHour().toPlainString() : "";
            item[8] = Objects.nonNull(data.getTripHour()) ? data.getTripHour().toPlainString() : "";
            item[9] = Objects.nonNull(data.getOutHour()) ? data.getOutHour().toPlainString() : "";
            item[10] = Objects.nonNull(data.getWorkOvertimeHour()) ? data.getWorkOvertimeHour().toPlainString() : "";
            item[11] = Objects.nonNull(data.getLateCount()) ? data.getLateCount().toString() : "";
            item[12] = Objects.nonNull(data.getEarlyCount()) ? data.getEarlyCount().toString() : "";
            item[13] = Objects.nonNull(data.getLakeCount()) ? data.getLakeCount().toString() : "";
            item[14] = Objects.nonNull(data.getAttendanceDay()) ? data.getAttendanceDay().toString() : "";
            item[15] = Objects.nonNull(data.getRealityAttendanceDay()) ? data.getRealityAttendanceDay().toString() : "";

            dataList.add(item);
        }
        POIUtils.exportExcel(httpServletResponse, "月度汇总记录", headers, dataList, "月度汇总记录");
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "schedulingAttendanceMonth:list")
    @Operation(summary = "分页获取月度考勤汇总列表 请开发者检查描述")
    public Response<Page<SchedulingAttendanceMonthDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = schedulingAttendanceMonthService.queryTotal(request.getParams());

        List<SchedulingAttendanceMonthDto> list = null;
        if (total > 0) {
            list = schedulingAttendanceMonthService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<SchedulingAttendanceMonthDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<SchedulingAttendanceMonthDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "schedulingAttendanceMonth:edit")
    @Operation(summary = "在编辑时根据id查询月度考勤汇总详情 请开发者检查描述")
    public Response<SchedulingAttendanceMonthDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (schedulingAttendanceMonthService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SchedulingAttendanceMonthDto schedulingAttendanceMonthDto = schedulingAttendanceMonthService.selectById(id);

        return Response.<SchedulingAttendanceMonthDto>ok().wrap(schedulingAttendanceMonthDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "schedulingAttendanceMonth:info")
    @Operation(summary = "根据id查询月度考勤汇总的详情 请开发者检查描述")
    public Response<SchedulingAttendanceMonthDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (schedulingAttendanceMonthService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SchedulingAttendanceMonthDto schedulingAttendanceMonthDto = schedulingAttendanceMonthService.selectById(id);

        return Response.<SchedulingAttendanceMonthDto>ok().wrap(schedulingAttendanceMonthDto);
    }

    /**
     * 保存
     *
     * @param schedulingAttendanceMonthDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "schedulingAttendanceMonth:edit")
    @Operation(summary = "新增月度考勤汇总 请开发者检查描述")
    public Response<Object> save(@RequestBody @Validated SchedulingAttendanceMonthDto schedulingAttendanceMonthDto) {

        //填充基础数据
        fillSaveCommonData(schedulingAttendanceMonthDto);

        schedulingAttendanceMonthService.save(schedulingAttendanceMonthDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param schedulingAttendanceMonthDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "schedulingAttendanceMonth:edit")
    @Operation(summary = "根据id修改月度考勤汇总 请开发者检查描述")
    public Response<Object> update(@RequestBody  @Validated SchedulingAttendanceMonthDto schedulingAttendanceMonthDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(schedulingAttendanceMonthDto.getId()));
        if (schedulingAttendanceMonthService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(schedulingAttendanceMonthDto);

        schedulingAttendanceMonthService.updateById(schedulingAttendanceMonthDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "schedulingAttendanceMonth:delete")
    @Operation(summary = "根据多条记录id批量删除月度考勤汇总 请开发者检查描述")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (schedulingAttendanceMonthService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        schedulingAttendanceMonthService.deleteBatch(ids);

        return Response.ok();
    }
}
